import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/widget/common/empty_tips.dart';
import 'package:material_collection_app/widget/common/refresh.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';
import 'package:material_collection_app/widget/message/message_card.dart';
import '../utils/utils.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MessagePage extends StatefulWidget  {
  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<MessagePage> {
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  List list = [];
  int currentPage = 1;
  int lastPage = 1;
  int total = 0;
  bool loadSuccess = false;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  // 加载数据
  _loadData({bool loadMore = false, bool screen}) async {
    loadSuccess = false;

    if(loadMore) { 
      currentPage++;
    }else {
      currentPage = 1;
    }

    Map params = {
      'page': currentPage,
    };

    DioUtils.request("common/getMyMsgList",
      context: context,
      method: "GET",
      params: params,
      onSuccess: (res) {
        if(res['code'] == 1) {
          if(mounted) {
            setState(() {
              if(loadMore) {
                list.addAll(res["data"]["data"]);
              }else {
                list = res["data"]["data"];
              }
              
              currentPage = res['data']['current_page'];
              lastPage = res['data']['last_page'];
              loadSuccess = true;
              total = res['data']['total'];
            });
          }
        }else {
          Utils.showText(text: res['msg']);
        }
      },
      onError: (error) {}
    );
  }

  // 下拉刷新
  _onRefresh() async{
    _refreshController.loadComplete();
    _loadData();

    await Future.delayed(Duration(milliseconds: 600));
    _refreshController.refreshCompleted();
  }

  // 加载更多
  _onLoading() async{
    await Future.delayed(Duration(milliseconds: 200));

    if(currentPage == lastPage) {
      _refreshController.loadNoData();
      return;
    }

    // 加载更多数据
    if(currentPage < lastPage) {
      _loadData(loadMore: true);
      _refreshController.loadComplete();
    }
  }

  Widget _buildPage() {
    // // 无数据
    if(loadSuccess && list.length == 0) {
      return EmptyTips(
        refreshController: _refreshController,
        onRefresh: _onRefresh,
        backgroundColor: Utils.hexToColor('#F7F6F9'),
      );
    }

    return ListView.builder(
      itemCount: list.length,
      padding: EdgeInsets.only(bottom: 60.w),
      itemBuilder: (BuildContext context, int index) {
        return MessageCard(item: list[index]);
      }
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
      appBar: TopBar(
        title: '消息通知',
        backgroundColor: Utils.hexToColor('#297CFF'),
      ),
      body: Container(
        color: Utils.hexToColor('#F5F6FA'),
        child: Column(
          children: <Widget>[
            Expanded(
              child: Container(
                padding: EdgeInsets.fromLTRB(25.w, 23.w, 25.w, 0),
                child: Refresh(
                  refreshController: _refreshController,
                  onRefresh: _onRefresh,
                  onLoading: _onLoading,
                  headBottom: 10,
                  child: _buildPage()
                )
              )
            )
          ]
        )
      )
    );
  }
}